package servlet;

import service.LessonService;
import service.RatifyLessonService;
import service.impl.LessonServiceImpl;
import service.impl.RatifyLessonServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/ratifyLessonApproveServlet")
public class RatifyLessonApproveServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String code = request.getParameter("code");
        String ifratify = request.getParameter("ifratify");
        String approve = request.getParameter("approve");
        String student = request.getParameter("student");
        String lessoncode = request.getParameter("lessoncode");

        if(approve.equals("1")){ifratify="2";}
        if(approve.equals("0")){ifratify="1";}

        if(approve.equals("3")){ifratify="3";}
        if(approve.equals("2")){ifratify="4";}

        RatifyLessonService rservice = new RatifyLessonServiceImpl();
        try {
            rservice.approve(code,student,lessoncode,ifratify);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        int statusint = Integer.parseInt(ifratify);

        if(statusint == 0||statusint == 2){statusint = 2;}
        else if(statusint == 1){statusint = 3;}
        else if(statusint == 3){statusint = 4;}
        else if(statusint == 4){statusint = 5;}

        String status = String.valueOf(statusint);

        boolean flag = false;
        LessonService service = new LessonServiceImpl();
        try {
            service.updatestatus(lessoncode,student,status,flag);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        HttpSession session = request.getSession();
        session.setAttribute("student",student);
        session.setAttribute("lessoncode",lessoncode);
        LessonService lessonService = new LessonServiceImpl();

        if(approve.equals("1")||approve.equals("3")) {
            try {
                lessonService.disapprove(lessoncode,student,"");
                rservice.disapprove(lessoncode,student,"");
                response.sendRedirect("/ratifyLessonListServlet");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else{
            response.sendRedirect("/disapprove.html");
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }
}